package org.example.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.award.event.SendAwardMessageEvent;
import org.example.domain.award.model.entity.DistributeAwardEntity;
import org.example.domain.award.service.IAwardService;
import org.example.types.event.BaseEvent;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SendAwardCustomer {

    @Value("${spring.rabbitmq.topic.send_award}")
    private String topic;

    @Resource
    private IAwardService awardService;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_award}"))
    public void listener(String message, Channel channel, Message amqpMessage) throws IOException {
        long deliveryTag = amqpMessage.getMessageProperties().getDeliveryTag();
        try {
            log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {}.getType());
            SendAwardMessageEvent.SendAwardMessage sendAwardMessage = eventMessage.getData();

            DistributeAwardEntity distributeAwardEntity = new DistributeAwardEntity();
            distributeAwardEntity.setUserId(sendAwardMessage.getUserId());
            distributeAwardEntity.setOrderId(sendAwardMessage.getOrderId());
            distributeAwardEntity.setAwardId(sendAwardMessage.getAwardId());
            distributeAwardEntity.setAwardConfig(sendAwardMessage.getAwardConfig());

            awardService.distributeAward(distributeAwardEntity);

            // 成功处理，手动ACK
            channel.basicAck(deliveryTag, false);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("对应的服务不存在")) {
                log.error("奖品服务不存在，跳过消息 topic: {} message: {}", topic, message, e);
                // 手动ACK，跳过该消息，避免无限重试
                channel.basicAck(deliveryTag, false);
            } else {
                log.error("监听用户奖品发送消息异常，准备重试 topic: {} message: {}", topic, message, e);
                // 拒绝消息，允许重试
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("监听用户奖品发送消息异常，准备重试 topic: {} message: {}", topic, message, e);
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
